﻿///
/// Neil Rees
/// iMeta Technologies
/// 11/12/08
/// 

using System;
using System.Threading;
using System.Diagnostics;
using PowerOn.WebService;

namespace PowerOn
{
    class Program
    {
        static int Main(string[] args)
        {
            // Check the args
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: poweron.exe url hostname");
                Console.WriteLine("");
                Console.WriteLine("Example: poweron.exe http://powerserver/powerservice.asmx myhost.contoso.com");
                return 1;
            }

            string wsURL = args[0];
            string hostName = args[1];

            WebService.PowerService ps = new PowerService();
            ps.Url = wsURL;

            bool packetSent = ps.PowerOn(hostName);

            if (!packetSent )
            {
                Console.WriteLine("Server has no record of " + hostName);
                return 2;
            }

            Console.WriteLine("Magic Packet Sent...");

            Stopwatch sw = new Stopwatch();
            sw.Start();

            bool awake = false;

            while (sw.Elapsed.TotalSeconds < Properties.Settings.Default.PowerOn_WakeTimeout)
            {
                awake = ps.IsAvailable(hostName);

                if (awake) break;

                Console.WriteLine(String.Format("{0} : Not responding yet...", hostName));
                Thread.Sleep(5000);
            }

            if (awake)            
            {
                Console.WriteLine(String.Format("{0} : Responded", hostName));
            }
            else
            {
                Console.WriteLine(String.Format("{0} : No reply", hostName));
                return 3;
            }

            return 0;
        }
    }
}
